package com.zscat.mallplus.center.controller;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zscat.mallplus.active.entity.CmsActive;
import com.zscat.mallplus.active.service.ICmsActiceService;
import com.zscat.mallplus.center.BaseController;
import com.zscat.mallplus.center.entity.CenterItem;
import com.zscat.mallplus.center.entity.CenterJifen;
import com.zscat.mallplus.center.entity.CenterRegisterItem;
import com.zscat.mallplus.center.service.ICenterItemService;
import com.zscat.mallplus.center.service.ICenterJifenService;
import com.zscat.mallplus.center.service.ICenterLevelService;
import com.zscat.mallplus.center.service.ICenterRegisterItemService;
import com.zscat.mallplus.center.vo.Face;
import com.zscat.mallplus.cms.entity.CmsSubject;
import com.zscat.mallplus.cms.service.ICmsSubjectService;
import com.zscat.mallplus.component.UserUtils;
import com.zscat.mallplus.pay.utils.StringUtils;
import com.zscat.mallplus.pay.utils.StringUtils.RandomType;
import com.zscat.mallplus.ums.entity.UmsMember;
import com.zscat.mallplus.ums.service.IUmsMemberService;
import com.zscat.mallplus.utils.CommonResult;
import com.zscat.mallplus.utils.RedisCache;
import com.zscat.mallplus.utils.SmsUtils;
import com.zscat.mallplus.utils.UserFaceAuthUtils;

@RestController
@RequestMapping("/center")
public class CenterController extends BaseController {

	@Resource
	private ICenterJifenService centerJifenService;
	@Resource
	private ICenterLevelService centerLevelService;
	@Resource
	private ICenterItemService centerItemService;
	@Resource
	private IUmsMemberService memberService;
	@Resource
	private ICenterRegisterItemService centerRegisterItemService;
	@Resource
	private RedisCache redisCache;
	@Resource
	private ICmsSubjectService subjectService;
	@Resource
	private ICmsActiceService acticeService;

	/**
	 * 身份证认证列表
	 */
	@GetMapping("/list")
	public Object list(CenterJifen centerJifen) {
		List<CenterJifen> list = centerJifenService.selectCenterJifenList(centerJifen);
		return new CommonResult().success(list);
	}

	/** 查询用户-积分-余额-等级 */
	@GetMapping(value = "/{userId}")
	public Object getInfo(@PathVariable("userId") Long userId) {
		return new CommonResult().success(this.isCenterJifen(userId));
	}

	/**
	 * 消费获得积分
	 */
	@GetMapping("update")
	public Object updat(CenterJifen cj) {
		CenterJifen centerJifen = this.isCenterJifen(cj.getUserId());
		if (cj.getMoney() > 0) {
			Long score = (long) (cj.getMoney() * 10) + centerJifen.getScore();
			centerJifen.setScore(score);
			Long score2 = centerLevelService.selectCenterLevelById(2L).getScore();// 2级所需积分
			Long score3 = centerLevelService.selectCenterLevelById(3L).getScore();// 3级所需积分
			if (score > score2) {
				centerJifen.setLevel(2);
			} else if (score > score3) {
				centerJifen.setLevel(3);
			}
			centerJifenService.updateCenterJifen(centerJifen);
			CenterItem item = new CenterItem();
			item.setUserId(cj.getUserId());
			item.setName("消费赠送");
			item.setIncome((double) score);
			item.setTime(new Date());
			item.setType(1);
			centerItemService.insertCenterItem(item);
		}
		return this.synchro(cj.getUserId());
	}

	/**
	 * 签到获得积分
	 */
	@GetMapping("register")
	public Object edit(Long userId) {
		CenterRegisterItem register = new CenterRegisterItem();
		CenterJifen centerJifen = this.isCenterJifen(userId);

		CenterItem item = new CenterItem();
		item.setUserId(userId);
		item.setName("每日签到");

		int regNum = centerJifenService.register(userId);
		if (regNum == 1) {
			Integer reg = centerJifen.getReg() + 1;
			centerJifen.setReg(reg);
			if (reg > 7) {
				centerJifen.setReg(1);
				item.setIncome(1.0);
				register.setScore(1L);
				reg = 1;
			}
			if (reg == 7) {
				centerJifen.setScore(centerJifen.getScore() + 10);
				item.setIncome(10.0);
				register.setScore(10L);
			} else {
				centerJifen.setScore(centerJifen.getScore() + reg);
				item.setIncome((double) reg);
				register.setScore((long) reg);
			}
		} else {
			centerJifen.setReg(1);
			item.setIncome(1.0);
			register.setScore(1L);
			centerJifen.setScore(centerJifen.getScore() + 1);
		}
		item.setTime(new Date());
		item.setType(1);
		centerItemService.insertCenterItem(item);
		centerJifen.setRegTime(new Date());
		// 判断积分与级别
		Long score = centerJifen.getScore();
		Long score2 = centerLevelService.selectCenterLevelById(2L).getScore();// 2级所需积分
		Long score3 = centerLevelService.selectCenterLevelById(3L).getScore();// 3级所需积分
		if (score > score2 && score < score3) {
			centerJifen.setLevel(2);
		} else if (score > score3) {
			centerJifen.setLevel(3);
		}

		register.setUserId(userId);
		register.setNickName(centerJifen.getNickName());
		register.setPhone(centerJifen.getPhone());
		register.setTime(new Date());
		centerRegisterItemService.insertCenterRegisterItem(register);
		if (centerJifenService.updateCenterJifen(centerJifen) > 0) {
			this.synchro(userId);
			return new CommonResult().success(centerJifenService.selectCenterJifenById(userId));
		} else {
			return new CommonResult().failed();
		}
	}

	/**
	 * 初始化积分、余额、等级属性信息
	 */
	private CenterJifen isCenterJifen(Long userId) {
		if (centerJifenService.selectCenterJifenById(userId) == null) {
			UmsMember member = memberService.getById(userId);
			CenterJifen centerJifen = new CenterJifen();
			centerJifen.setUserId(userId);
			centerJifen.setNickName(member.getNickname() == null ? "" : member.getNickname());
			centerJifen.setPhone(member.getPhone() == null ? "" : member.getPhone());
			centerJifenService.insertCenterJifen(centerJifen);
		}
		return centerJifenService.selectCenterJifenById(userId);
	}

	/**
	 * 会员信息同步属性表
	 */
	private CommonResult synchro(Long userId) {
		CenterJifen centerJifen = centerJifenService.selectCenterJifenById(userId);
		UmsMember member = memberService.getById(userId);
		member.setIntegration(centerJifen.getScore().intValue());
		member.setBlance(new BigDecimal(centerJifen.getMoney()));
		member.setMemberLevelId((long) centerJifen.getLevel());
		return toAjax(memberService.updateById(member));
	}

	/**
	 * 实名认证
	 */
	@PostMapping("userFace")
	public Object userFace(@RequestBody Face face) {
		System.out.println(face.getBase64());
		System.out.println(face.getUserId());
		CenterJifen centerJifen = this.isCenterJifen(face.getUserId());
		boolean a = UserFaceAuthUtils.face(face.getBase64(), face.getName(), face.getCode(), true);
		if (a) {
			centerJifen.setIsreal(1);
			centerJifen.setRealName(face.getName());
			centerJifen.setIdNumber(face.getCode());
			centerJifen.setImg1(face.getImg1());
			centerJifen.setImg2(face.getImg2());
			centerJifen.setImg3(face.getImg3());
			centerJifen.setRealTime(new Date());
			centerJifenService.updateCenterJifen(centerJifen);
			return new CommonResult().success(centerJifenService.selectCenterJifenById(face.getUserId()));
		} else {
			return new CommonResult().failed("认证失败");
		}
	}

	/**
	 * 充值 消费 积分 余额
	 */
	@PutMapping
	public Object edit(@RequestBody CenterJifen centerJifen, int type) {
		CenterJifen jifen = this.isCenterJifen(centerJifen.getUserId());
		CenterItem item = new CenterItem();
		item.setUserId(centerJifen.getUserId());
		if (centerJifen.getMoney() != null || type == 2) {
			item.setType(2);
			jifen.setMoney(centerJifen.getMoney() + jifen.getMoney());
			if (centerJifen.getMoney() > 0) {
				item.setIncome(centerJifen.getMoney());
				item.setName("余额充值");
			} else if (centerJifen.getMoney() < 0) {
				item.setPay(centerJifen.getMoney());
				item.setName("余额消费");
			}
		} else if (centerJifen.getScore() != null || type == 1) {
			item.setType(1);
			jifen.setScore(centerJifen.getScore() + jifen.getScore());
			if (centerJifen.getScore() > 0) {
				item.setIncome((double) centerJifen.getScore());
				item.setName("积分充值");
			} else if (centerJifen.getScore() < 0) {
				item.setPay((double) centerJifen.getScore());
				item.setName("积分消费");
			}
		} else {
			return new CommonResult().failed();
		}
		return centerJifenService.updateCenterJifen(centerJifen) > 0 ? this.synchro(centerJifen.getUserId())
				: new CommonResult().failed();
	}

	/**
	 * 查询签到明细列表
	 */
	@GetMapping("/register/list")
	public Object list(CenterRegisterItem centerRegisterItem) {
		List<CenterRegisterItem> list = centerRegisterItemService.selectCenterRegisterItemList(centerRegisterItem);
		return new CommonResult().success(list);
	}

	/**
	 * 获取短信
	 */
	@RequestMapping("/getMessage")
	public Object getMessage(@RequestParam(required = true) String phone) {
		try {
			// 校验
			if (phone != null) {
				String regex = "^\\d{11}$";
				Pattern p = Pattern.compile(regex);
				Matcher m = p.matcher(phone);
				if (!m.matches()) {
					return new CommonResult().success("手机号校验未通过");
				}
			}
			String message = StringUtils.random(6, RandomType.INT);
			String phone86 = "+86" + phone;
			String[] phoneNumbers = { phone86 };
			String[] templateParams = { message, "2" };
			String templateID = "690299";
			SmsUtils.sendSms(phoneNumbers, templateParams, templateID);
			redisCache.setCacheObject("SMS_AUTH:" + phone, message, 2, TimeUnit.MINUTES);
		} catch (Exception e) {
			e.printStackTrace();
			return new CommonResult().failed(e.getMessage());
		}
		return new CommonResult().success();
	}

	/**
	 * 手机号认证
	 * 
	 * @param Wsen
	 */
	@GetMapping("/isMessage")
	public Object isMessage(@RequestParam(required = true) String phone, @RequestParam(required = true) String msg) {
		String redisCode = (String)redisCache.getCacheObject("SMS_AUTH:" + phone);
		if (StringUtils.isNotBlank(redisCode)) {
			if (msg.equals(redisCode)) {
				CenterJifen center = new CenterJifen();
				center.setUserId(getUser().getId());
				center.setIsPhone(1);
				center.setPhone(phone);
				UmsMember member = memberService.getById(center.getUserId());
				List<UmsMember> list = memberService.list(new QueryWrapper<UmsMember>().eq("validate_phone", phone));
				if (null == list || list.isEmpty()) {
//					member.setPhone(phone);
					member.setValidatePhone(phone);
					centerJifenService.updateCenterJifen(center);
				} else {
					return new CommonResult().success("手机号已认证");
				}
				memberService.updateById(member);
				return new CommonResult().success("认证成功");
			} else {
				return new CommonResult().failed("验证码错误");
			}
		}
		return new CommonResult().failed("验证码失效");
	}
	
	/**
	 * 文章转发、点击统计
	 * @param operationType 操作类型   1、点击   2、转发
	 * @param type	文章类型	1、科普   2、（研学、创客、活动）
	 * @param id	文章编号
	 * @return
	 */
	@GetMapping("/subject/count")
	public Object count(@RequestParam(value = "operationType", required = true) Integer operationType,
						@RequestParam(value = "type", required = true) Integer type,
						@RequestParam(value = "id", required = true) Long id ) {
		UmsMember member = UserUtils.getCurrentMember();
		if (null == member) {
			return new CommonResult().failed("获取用户信息失败。");
		}
		if (type == 1) {
			CmsSubject subject = subjectService.getById(id);
			if (operationType == 1) {
				Integer readCount = subject.getReadCount() == null? 0:subject.getReadCount();
				subject.setReadCount(readCount + 1);
			}else if(operationType == 2){
				Integer forwardCount = subject.getForwardCount()==null? 0: subject.getForwardCount();
				subject.setForwardCount(forwardCount + 1);
			}
			if (!subjectService.updateById(subject)) {
				return new CommonResult().failed("统计失败");
			}
		}else if (type == 2) {
			CmsActive active = acticeService.getById(id);
			if (operationType == 1) {
				Integer likeCount = active.getLikeCount()==null? 0:active.getLikeCount();
				active.setLikeCount(likeCount + 1);
			}else if (operationType == 2) {
				Integer forwardCount = active.getForwardCount()==null? 0:active.getForwardCount();
				active.setForwardCount(forwardCount + 1);
			}
			if (!acticeService.updateById(active)) {
				return new CommonResult().failed("统计失败");
			}
		}
		
		return new CommonResult().success();
	}
	
}
